/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.zhihu.visit.service.impl;

import cn.hutool.core.lang.Console;
import me.zhengjie.modules.zhihu.common.ListUtils;
import me.zhengjie.modules.zhihu.question.repository.ZhihuQuestionRepository;
import me.zhengjie.modules.zhihu.question.service.ZhihuQuestionService;
import me.zhengjie.modules.zhihu.question.service.dto.ZhihuQuestionDto;
import me.zhengjie.modules.zhihu.question.service.dto.ZhihuQuestionQueryCriteria;
import me.zhengjie.modules.zhihu.visit.callable.VisitNumCallable;
import me.zhengjie.modules.zhihu.visit.domain.ZhQuestionVisit;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.zhihu.visit.repository.ZhQuestionVisitRepository;
import me.zhengjie.modules.zhihu.visit.service.ZhQuestionVisitService;
import me.zhengjie.modules.zhihu.visit.service.dto.ZhQuestionVisitDto;
import me.zhengjie.modules.zhihu.visit.service.dto.ZhQuestionVisitQueryCriteria;
import me.zhengjie.modules.zhihu.visit.service.mapstruct.ZhQuestionVisitMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author 王超
* @date 2022-01-12
**/
@Service
@RequiredArgsConstructor
public class ZhQuestionVisitServiceImpl implements ZhQuestionVisitService {

    private final ZhQuestionVisitRepository zhQuestionVisitRepository;
    private final ZhihuQuestionRepository zhihuQuestionRepository;

    private final ZhQuestionVisitMapper zhQuestionVisitMapper;

    @Autowired
    private ZhihuQuestionService zhihuQuestionService;
//    @Autowired
//    private RedisTemplate redisTemplate;

    private static DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd");


    @Override
    public Map<String,Object> queryAll(ZhQuestionVisitQueryCriteria criteria, Pageable pageable){
        Page<ZhQuestionVisit> page = zhQuestionVisitRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(zhQuestionVisitMapper::toDto));
    }

    @Override
    public List<ZhQuestionVisitDto> queryAll(ZhQuestionVisitQueryCriteria criteria){
        return zhQuestionVisitMapper.toDto(zhQuestionVisitRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ZhQuestionVisitDto findById(String id) {
        ZhQuestionVisit zhQuestionVisit = zhQuestionVisitRepository.findById(id).orElseGet(ZhQuestionVisit::new);
        ValidationUtil.isNull(zhQuestionVisit.getId(),"ZhQuestionVisit","id",id);
        return zhQuestionVisitMapper.toDto(zhQuestionVisit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZhQuestionVisitDto create(ZhQuestionVisit resources) {
        return zhQuestionVisitMapper.toDto(zhQuestionVisitRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ZhQuestionVisit resources) {
        ZhQuestionVisit zhQuestionVisit = zhQuestionVisitRepository.findById(resources.getId()).orElseGet(ZhQuestionVisit::new);
        ValidationUtil.isNull( zhQuestionVisit.getId(),"ZhQuestionVisit","id",resources.getId());
        zhQuestionVisit.copy(resources);
        zhQuestionVisitRepository.save(zhQuestionVisit);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            zhQuestionVisitRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ZhQuestionVisitDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ZhQuestionVisitDto zhQuestionVisit : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("当前日期浏览数", zhQuestionVisit.getVisitNum());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void calc(String themeId) {
        LocalDateTime date=LocalDateTime.now();
        AtomicInteger count = new AtomicInteger(0);
        List<ZhQuestionVisit> visits = new ArrayList<>();
        ZhihuQuestionQueryCriteria param = new ZhihuQuestionQueryCriteria();
        Timestamp timestamp = new Timestamp((new Date()).getTime());
        param.setVisitDate(timestamp);
        param.setThemeId(themeId);
        List<String> questions = this.zhihuQuestionRepository.findByVisitDate(date.format(formatter),themeId);
        List<List<String>> groupList = new ArrayList<>();
        //List<String> range = redisTemplate.opsForList().range("ip", 0, -1);

        if (questions.size() > 0 && questions.size() < 200) {
            groupList.add(questions);
        } else {
            groupList = ListUtils.partition(questions, 200);
        }

        ExecutorService es = Executors.newFixedThreadPool(2);

        List<Future> futures = new ArrayList<>();
        for (List<String> ids : groupList) {
            //List<String> ids = questionList.stream().map(ZhihuQuestionDto::getId).collect(Collectors.toList());
            VisitNumCallable visitNumCallable = new VisitNumCallable(ids, count);
            futures.add(es.submit(visitNumCallable));
        }

        futures.forEach(future -> {
            try {
                visits.addAll((List)future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
//
//        List<List<ZhQuestionVisit>> zhQuestionVisits = new ArrayList();
//        if (visits.size() > 0 && visits.size() < 200) {
//            (zhQuestionVisits).add(visits);
//        } else {
//            zhQuestionVisits = ListUtil.partition(visits, GROUP_SIZE);
//        }
//
//        Iterator var14 = ((List)zhQuestionVisits).iterator();
//
//        while(var14.hasNext()) {
//            List<ZhQuestionVisit> zhQuestionVisit = (List)var14.next();
//            this.questionVisitMapper.batchIsertQuestionVisit(zhQuestionVisit);
//        }

        es.shutdown();
        Console.log("恭喜你，全部转换完成，当前线程池已关闭：{},成功转化总计{}条", new Object[]{Thread.currentThread().getName(), count.addAndGet(1)-1});

    }
}
